/**
 *
 */
package com.ybkj.daijia.server.service.impl;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.common.Pager;
import com.ybkj.daijia.common.Principal;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.config.SalesApi;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.page.Pageable;
import com.ybkj.daijia.page.impl.PageImpl;
import com.ybkj.daijia.page.impl.PageRequest;
import com.ybkj.daijia.server.errand.OrderType;
import com.ybkj.daijia.server.mapper.CompanyMapper;
import com.ybkj.daijia.server.mapper.CouponRuleMapper;
import com.ybkj.daijia.server.sales.CouponRule;
import com.ybkj.daijia.server.service.CouponRuleService;
import com.ybkj.daijia.server.service.ErrandUpService;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

/**
 * @author Shine
 *
 */
@Service
public class DefaultCouponRuleService implements CouponRuleService {

    @Autowired
    private SalesApi salesApi;
    @Autowired
    private SettingUtils settingUtils;
    @Autowired
    private CompanyMapper companyMapper;
    @Autowired
    private CouponRuleMapper couponRuleMapper;
    @Autowired
    private ErrandUpService errandService;

    @Override
    public List<CouponRule> listValid() {

        Subject currentUser = SecurityUtils.getSubject();
        Principal principal = (Principal) currentUser.getPrincipal();

        StringBuilder builder = new StringBuilder();
        builder.append(salesApi.getCouponRuleBaseURL() + SalesApi.FINDVALID_COUPONRULE
            + ".json?appKey={appKey}&appId={appId}&sign={sign}");
        Map<String, String> kv = new HashMap<String, String>();

        kv.put("companyId", String.valueOf(principal.getCompanyId()));
        builder.append("&companyId={companyId}");

        String result = salesApi.get(builder.toString(), kv, settingUtils.get());
        List<com.ybkj.daijia.server.sales.CouponRule> list = new ArrayList<com.ybkj.daijia.server.sales.CouponRule>();
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONArray data = jo.getJSONArray("data");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(data.toString(),
                    new TypeToken<List<com.ybkj.daijia.server.sales.CouponRule>>() {
                    }.getType());
                for (com.ybkj.daijia.server.sales.CouponRule couponRule : list) {
                    couponRule
                        .setCompany(companyMapper.selectByPrimaryKey(couponRule.getCompanyId()));
                }

            }

        }

        return list;

    }

    @Override
    public Result<CouponRule> insert(String title, String code, Date start, Date end,
        Long companyId, Integer type, String couponType, Long couponTypeId,
        Double discount, BigDecimal money, Integer number,
        Integer eachLimit) {
        Result<CouponRule> result = new Result<CouponRule>();

        MultiValueMap<String, String> kv = new LinkedMultiValueMap<String, String>();
        kv.add("title", title);
        kv.add("code", code);
        kv.add("couponType", couponType);
        if (null != couponTypeId) {
            kv.add("couponTypeId", String.valueOf(couponTypeId));
        }
        kv.add("start", String.valueOf(start.getTime()));
        if (end != null) {
            kv.add("end", String.valueOf(end.getTime()));
        }
        kv.add("companyId", String.valueOf(companyId));
        kv.add("type", String.valueOf(type));

        if (type == 0) {

            if (discount != null) {

                kv.add("discount", String.valueOf(discount));
            }

        } else {

            if (money != null) {

                kv.add("money", String.valueOf(money));
            }

        }

        kv.add("number", String.valueOf(number));
        kv.add("eachLimit", String.valueOf(eachLimit));

        String result1 = salesApi
            .post(salesApi.getCouponRuleBaseURL() + SalesApi.CREATE_COUPONRULE, kv,
                settingUtils.get());
        JSONObject jo = new JSONObject(result1);
        Integer code1 = jo.getInt("code");
        if (code1 == 0) {
            JSONObject data = jo.getJSONObject("data");
            Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
            CouponRule couponRule = gson.fromJson(data.toString(), CouponRule.class);
            result.setResult(couponRule);
            result.setSuccess(true);
        } else {
            result.setMessage(jo.getString("message"));
        }
        return result;
    }

    @Override
    public Page<CouponRule> queryCouponRule() {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        Pageable pageable = new PageRequest(Pager.getPage(), Pager.getLimit());

        StringBuilder builder = new StringBuilder();
        builder.append(salesApi.getCouponRuleBaseURL() + SalesApi.FINDALL_COUPONRULE
            + ".json?appKey={appKey}&appId={appId}&sign={sign}&page={page}&rows={rows}");
        Map<String, String> kv = new HashMap<String, String>();
        kv.put("page", String.valueOf(Pager.getPage() + 1));
        kv.put("rows", String.valueOf(Pager.getLimit()));
        if (!principal.isCompanyType()) {
            kv.put("companyId", String.valueOf(principal.getCompanyId()));
            builder.append("&companyId={companyId}");
        }

        String result = salesApi.get(builder.toString(), kv, settingUtils.get());

        List<CouponRule> list = new ArrayList<CouponRule>();
        long total = 0;
        if (null != result) {
            JSONObject jo = new JSONObject(result);
            Integer code = jo.getInt("code");
            if (code == 0) {
                JSONObject data = jo.getJSONObject("data");
                total = data.getLong("total");
                JSONArray ja = data.getJSONArray("rows");
                Gson gson = new GsonBuilder().setDateFormat(com.ybkj.daijia.constant.DateConstant.DATE_TIME_FORMATE).create();
                list = gson.fromJson(ja.toString(), new TypeToken<List<CouponRule>>() {
                }.getType());
                for (CouponRule couponRule : list) {
                    couponRule
                        .setCompany(companyMapper.selectByPrimaryKey(couponRule.getCompanyId()));
                    if (couponRule.getCouponType().equals(CouponRule.CouponType.paotui)
                        && null != couponRule.getCouponTypeId()) {
                        OrderType orderType = errandService
                            .findByTypeId(couponRule.getCouponTypeId());
                        String couponTypeName = "";
                        if (null != orderType) {
                            couponTypeName = orderType.getTypeName();
                        }

                        couponRule.setCouponTypeName(couponTypeName);
                    }
                }

            }

        }

        return new PageImpl<CouponRule>(list, pageable, total);
    }


    @Override
    public CouponRule findOne(Long id) {

        Result<CouponRule> result = salesApi.findOneCouponRule(id);

        return result.getResult();

    }


    @Override
    public Integer deleteCouponRule(Long id) {
        int i = 0;
        StringBuilder builder = new StringBuilder();
        builder.append(salesApi.getCouponRuleBaseURL() + SalesApi.DELETE_COUPONRULE
            + "?id={id}&appKey={appKey}&appId={appId}&sign={sign}");

        Map<String, String> kv = new HashMap<String, String>();
        kv.put("id", String.valueOf(id));
        String result = salesApi.delete(builder.toString(), kv, settingUtils.get());

        return i;

    }

    @Override
    public Integer updateCouponRuleLapsed(Long id) {
        int i = 0;
        StringBuilder builder = new StringBuilder();
        builder.append(salesApi.getCouponRuleBaseURL() + SalesApi.LAPSED_COUPONRULE
            + "?id={id}&appKey={appKey}&appId={appId}&sign={sign}");

        Map<String, String> kv = new HashMap<String, String>();
        if (null != id) {
            kv.put("id", String.valueOf(id));
        }
        String result = salesApi.put(builder.toString(), kv, settingUtils.get());

        return i;
    }

    @Override
    public List<com.ybkj.daijia.server.model.CouponRule> listAllOld() {
        return couponRuleMapper.listAllOld();
    }


}
